package usdt

import (
	"coinsend/btc"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"

	"github.com/tidwall/gjson"
)

type JsonBalance struct {
	Balance []JsonData `json:"balance"`
}

type JsonData struct {
	Symbol string `json:"symbol"`
	Value  string `json:"value"`
}

//USDT查询订单状态
func GetUSDTCheckHash(hash string) int {
	var url = "https://api.omniexplorer.info/v1/transaction/tx/" + hash
	resp, err := http.Get(url)
	if err != nil {
		return 0
	}
	defer resp.Body.Close()
	input, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0
	}
	obj := gjson.ParseBytes(input)
	confirmations := obj.Get("confirmations").Int()
	return int(confirmations)
}

//获取USDT地址余额
func Getaddressbalance(addr string) float64 {
	var jsondata JsonBalance
	my_url := "https://api.omniexplorer.info/v1/address/addr/"

	resp, err := http.PostForm(my_url, url.Values{"addr": {addr}})

	if err != nil {
		return 0
	}
	defer resp.Body.Close()
	input, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return 0
	}
	json.Unmarshal([]byte(input), &jsondata)

	for k, _ := range jsondata.Balance {
		if jsondata.Balance[k].Symbol == "SP31" {
			balance, _ := strconv.ParseFloat(jsondata.Balance[k].Value, 64)
			return balance / 100000000.0
		}
	}
	return 0
}

func GetUsdtUnsign(from string, to string, amount, fee float64) (string, error) {
	balance := Getaddressbalance(from)

	if balance < amount {
		return "", errors.New(from + "USDT 余额不足")

	}

	//构造usdt转账协议
	h := fmt.Sprintf("%x", int(amount*100000000.0))
	l := len(h)
	for i := 0; i < 16-l; i++ {
		h = "0" + h
	}
	usdt_OP_RETURN := "OP_RETURN 6f6d6e69000000000000001f" + h

	return btc.CommandGlobal.PayToUsdt(from, usdt_OP_RETURN, to, fee)

}
